<?php
  include('header.php');
  include('functions.php');
  if ($_SERVER['REQUEST_METHOD'] != 'POST') {
      //someone is calling the file directly, which we don't want
      echo 'This file cannot be called directly.';
      header('location: index.php');
  } else {
      $result = $db->query("SELECT topic_status FROM " . $table_prefix . "topics WHERE topic_id = " . mysql_real_escape_string($_GET['t']) . ""); $qqq+=1;
      $check_status = $db->fetch_array($result,'assoc');
      if ($check_status['topic_status'] == 1 and $_SESSION['user_level'] < 1) {
          echo '<hr><br/><div align="center">' . $l_error_tlocked . ' </div>';
      } else {
          if (!$_SESSION['signed_in'] and $captcha_for_guests == "1") {
              $key = substr($_SESSION['key'], 0, 5);
              $number = $_REQUEST['number'];
              if ($number != $key) {
                  echo "<hr><br/><div align='center'><span style='color:red'>$l_error_captcha<br />";
                  echo '<br /><a href="topic.php?t='.$topicid.'&page='.$page.'">' . $l_back_to_prev . '</a></span></div><br />';
                  die;
              }
          }
          //check for sign in status
          if (!$_SESSION['signed_in'] and $allow_guest_posts == "0") {
              echo '<hr><br/><div align="center">' . $l_error_signin . '</div>';
          } else {
              //a real user posted a real reply
              $blah = $_POST["reply"];
              if ((strlen($blah) < $min_post_characters)) {
                  echo "<hr><br/><div align=\"center\"><span style='color:red'>$l_message_few<br /><br /></span>
<a href='topic.php?t=$topicid&page=$page'>$l_back_to_prev</a></span></div><br /></div><br>";
                  die;
              } else {
                  if ((strlen($blah) > $max_post_characters)) {
                      echo "<hr><br/><div align=\"center\"><span style='color:red'>$l_message_many<br /><br /></span>
<a href=\"#reply\" onClick='history.go(-1)'>$l_back_to_prev</a></div>";
                  } else {
                      $text = $_POST['reply'];
                      //$text = strip_tags($_POST['reply']);
                      //$file = remote_filesize($text,'',''); echo ceil($file/1024);
					  $text = my_nl2br($text); //Remove double or miltiple new lines
                      $text = convEnt2($text);
                      $text = str_replace("[b][b]", "[b]", $text);
                      $text = str_replace("[/b][/b]", "[/b]", $text);
                      //Disable smilies in post?
                      $disable_smilies = "0";
                      if (isset($_POST['dissmilies']) && $_POST['dissmilies'] == 'on') {
                          $disable_smilies = "1";
                          $text = DisableSmilies($text);
                      }
					  $text = DisableSmilies($text);
                      //$text = str_replace ("[img]","[url]",$text );
                      //$text = str_replace ("[/img]","[/url]",$text );
                      //Parse BBCodes
                      $text = str_replace("\n", "<br>", $text);
					  if (!isset($_POST['dissbb'])){
                          $text = BBCode($text);
                      }

                      $result1 = $db->query("SELECT topic_id, topic_subject, topic_cat, topic_starter, reply FROM " . $table_prefix . "topics WHERE topics.topic_id = " . mysql_real_escape_string($_GET['t'])); $qqq+=1;
                      $result2 = $db->query("SELECT post_by, post_topic FROM " . $table_prefix . "posts WHERE post_topic = " . mysql_real_escape_string($_GET['t']) . ""); $qqq+=1;
                      $tsubject = $db->fetch_array($result1,'assoc');
                      $perma_link = mysql_num_rows($result2) + 1;
                      $pages = ceil($perma_link / $post_per_page);
                      if (!$_SESSION['user_id']) {
                          $_SESSION['user_id'] = 1;
                      } else {
                          $uid = 0;
                      }
					  
					  $user = $db->query("SELECT user_name, user_posts, user_id  FROM " . $table_prefix . "users WHERE user_id = " . $_SESSION['user_id'] . "");
                      $userposted = $db->fetch_array($user,'assoc'); $qqq+=1;
					  
					  $approve = 0;
					  //IF post need approval and user is NOT admin or mod
					  if ($post_approve == 1 AND $_SESSION['user_level']<1 AND $userposted['user_posts']<$auto_approve_after_posts) {$approve = 1;}
					  if ($post_approve == 1 AND $_SESSION['user_level']<1 AND $auto_approve_after_posts == 0) {$approve = 1;}
                      $userIP = $_SERVER["REMOTE_ADDR"];
                      $result = $db->query("INSERT INTO " . $table_prefix . "posts(post_subject, post_content, post_date, post_topic, post_by, post_smilies, poster_ip, post_cat,post_page,post_approve) VALUES ('" . $tsubject['topic_subject'] . "','" . $text . "', NOW() + INTERVAL " . $server_time . " MINUTE + INTERVAL " . $time_difference . " HOUR, " . mysql_real_escape_string($_GET['t']) . ", " . $_SESSION['user_id'] . ", " . $disable_smilies . ", '" . $userIP . "'," . $tsubject['topic_cat'] . ",$pages, $approve)"); $qqq+=1;
                      $postid = mysql_insert_id();
                      if (!$result) {
                          echo 'Your reply has not been saved, please try again later.';
                          die;
                      }
                      
                      $result4 = $db->query("UPDATE " . $table_prefix . "topics SET topic_last_poster='" . $userposted['user_name'] . "', topic_last_post_date= NOW() + INTERVAL " . $server_time . " MINUTE + INTERVAL " . $time_difference . " HOUR, reply=" . mysql_num_rows($result2) . ", topic_last_poster_id = " . $_SESSION['user_id'] . "  WHERE topic_id=" . mysql_real_escape_string($_GET['t'])); $qqq+=1;
                      $result5 = $db->query("UPDATE " . $table_prefix . "users SET user_posts=user_posts+1 WHERE user_id = " . $_SESSION['user_id'] . ""); $qqq+=1;
                      
                      //UPDATE categories
                      //all topics
                      $result44 = $db->query("SELECT reply FROM " . $table_prefix . "topics WHERE topic_cat = " . $tsubject['topic_cat'] . "");
                      $topics = mysql_num_rows($result44); $qqq+=1;
                      //all replies
                      $result55 = $db->query("SELECT SUM(reply) FROM " . $table_prefix . "topics WHERE topic_cat = " . $tsubject['topic_cat'] . ""); $qqq+=1;
                      $row5 = $db->fetch_array($result55,'assoc');
                      $num_replies = $row5['SUM(reply)'];
                      
                      $result5 = $db->query("UPDATE " . $table_prefix . "categories SET cat_last_post_id=" . mysql_real_escape_string($_GET['t']) . ", cat_last_poster_id=" . $_SESSION['user_id'] . ",cat_last_post_subject='" . $tsubject['topic_subject'] . "',cat_last_post_time=NOW() + INTERVAL " . $server_time . " MINUTE + INTERVAL " . $time_difference . " HOUR, cat_last_poster_name='" . $userposted['user_name'] . "',cat_posts=$num_replies,cat_topics=$topics WHERE cat_id = " . $tsubject['topic_cat'] . "") or die(mysql_error()); $qqq+=1;
                      
                      //Cache this post
                      if ($forum_cache == 1) {
                          $time = strtotime($time_difference . " hours");
                          $cache = "./cache/forum" . $tsubject['topic_cat'] . ".php";
                          $FileHandle = fopen($cache, 'w') or die("can't open file");
                          fwrite($FileHandle, "ForumID = " . $tsubject['topic_cat'] . "");
                          fwrite($FileHandle, "\nTopicID = " . mysql_real_escape_string($_GET['t']) . "");
                          fwrite($FileHandle, "\nLast Topic = " . $tsubject['topic_subject'] . "");
                          fwrite($FileHandle, "\nTopic date = " . date($date_format, $time) . "");
                          fwrite($FileHandle, "\nTopic by = " . $userposted['user_name'] . "");
                          fwrite($FileHandle, "\nUserID = " . $_SESSION['user_id'] . "");
                          
                          fwrite($FileHandle, "\nTopics = " . $topics . "");
                          fwrite($FileHandle, "\nReplies = " . $num_replies . "");
                          fclose($FileHandle);
                      }
                      //Cache this topic
                      
                      
                      if (!$result) {
                          echo 'Your reply has not been saved, please try again later.';
                      } else {
                          $topic_page = $pages;
                          if ($topic_page == "") {
                              $topic_page = 1;
                          }
                          //CHECK notifications
                          $result = $db->query("SELECT * FROM " . $table_prefix . "topics_watch WHERE topic_id = " . $tsubject['topic_id'] . " AND user_id !=" . $_SESSION['user_id'] . " AND status = 0");
                          if (mysql_num_rows($result) <= 0) { 
                              echo ""; $qqq+=1;
                          } else {
                              while ($row = $db->fetch_array($result,'assoc')) {
                                  $result2 = $db->query("SELECT  user_email, user_name FROM " . $table_prefix . "users WHERE user_id = " . $row['user_id'] . "") or die(mysql_error()); $qqq+=1;
                                  $row2 = $db->fetch_array($result2,'assoc');
                                  $result3 = $db->query("UPDATE " . $table_prefix . "topics_watch SET status = 1 WHERE user_id = " . $row['user_id'] . ""); $qqq+=1;
                                  
                                  //echo $row2['user_email']." - ".$row2['user_name']."<br>";
                                  $email = $row2['user_email'];
                                  $url = "http://" . $_SERVER["SERVER_NAME"] . dirname($_SERVER["PHP_SELF"]) . "/topic.php?t=" . $tsubject['topic_id'] . "&page=" . $pages;
                                  $unnotify = "http://" . $_SERVER["SERVER_NAME"] . dirname($_SERVER["PHP_SELF"]) . "/topic.php?t=" . $tsubject['topic_id'] . "&unnotify=" . $tsubject['topic_id'];
                                  
                                  $subject = "Topic reply: " . $tsubject['topic_subject'];
                                  $message = "$l_email_message1 " . $row2['user_name'] . ",\r\n\r\n";
                                  $message .= "$l_email_notify1 " . $tsubject['topic_starter'] . ". \r\n\r\n";
                                  $message .= "$l_email_notify2 " . $url . "#$postid\r\n\r\n";
                                  $message .= "$l_email_notify3 " . $unnotify . "\r\n\r\n";
                                  $message .= $l_email_notify4;
                                  
                                  if ($smtp == "local") {
                                      $myemail = $smtp_username;
                                      //$row2['user_email'];    //"$_POST[user_email]";
                                      $to = $row2['user_email'];
                                      $subject = $subject;
                                      $sendmessage = $message;
                                      $headers = "From: $l_forumname<$myemail>" . "\r\n" . "Reply-To: $myemail" . "\r\n" . 'X-Mailer: PHP/' . phpversion();
                                      $sentmail = mail($to, $subject, $sendmessage, $headers);
                                  }
                                  //END LOCAL mail
                                  //SMTP MAIL
                                  if ($smtp == "smtp") {
                                      error_reporting(E_STRICT);
                                      date_default_timezone_set('America/Toronto');
                                      require_once('./phpmailer/class.phpmailer.php');
                                      $mail = new PHPMailer();
                                      
                                      $body = "Hello " . $row2['user_name'] . ",\r\n\r\n<br /><br />";
                                      $body .= "$l_email_notify1 " . $tsubject['topic_starter'] . ". \r\n\r\n<br /><br />";
                                      $body .= "$l_email_notify2 " . $url . "#$postid\r\n\r\n<br /><br />";
                                      $body .= "$l_email_notify3 " . $unnotify . "\r\n\r\n<br /><br />";
                                      $body .= $l_email_notify4;
                                      $body = preg_replace("#[\]#", '', $body);
                                      
                                      // telling the class to use SMTP
                                      $mail->IsSMTP();
                                      // SMTP server
                                      $mail->Host = $smtp_server;
                                      // enables SMTP debug information (for testing)
                                      $mail->SMTPDebug = 1;
                                      // 1 = errors and messages, 2 = messages only
                                      // enable SMTP authentication
                                      $mail->SMTPAuth = true;
                                      // sets the SMTP server
                                      $mail->Host = $smtp_server;
                                      $mail->SMTPSecure = $smtp_secure;
                                      // set the SMTP port for the GMAIL server
                                      $mail->Port = $smtp_port;
                                      // SMTP account username
                                      $mail->Username = $smtp_username;
                                      // SMTP account password
                                      $mail->Password = $smtp_password;
                                      
                                      $mail->SetFrom($smtp_username, $l_forumname);
                                      $mail->AddReplyTo($row2['user_email'], $l_forumname);
                                      $mail->Subject = "$l_email_notify_subject " . $tsubject['topic_subject'];
                                      // optional, comment out and test
                                      $mail->AltBody = "$l_email_alt_body";
                                      $mail->MsgHTML($body);
                                      $address = $row2['user_email'];
                                      $mail->AddAddress($address, $row2['user_name']);
                                      
                                      if (!$mail->Send()) {
                                          echo "Mailer Error: " . $mail->ErrorInfo;
                                      }
                                  }
                                  //END SMTP MAIL
                                  
                              }
                          }
                          echo '<hr/><br/><div align="center">' . $l_posted_success . '<br /><br /> <a class="loginlink" href="topic.php?t=' . mysql_real_escape_string($_GET['t']) . '&page=' . $topic_page . '#' . $postid . '">' . $l_view_message . '</a>.<br /><a class="loginlink" href="category.php?f=' . $tsubject["topic_cat"] . '"><br /> ' . $l_return_to . '</a>. </div><br />';
                          $hide_footer = 1; 
                      }
                  }
              }
          }
      }
  }
  if (!isset($pageContents)) {
      $pageContents = $l_forumname;
  }
  $pageContents = ob_get_contents();
  ob_end_clean();
  echo str_replace('<!--TITLE-->', $pageTitle, $pageContents);
  if ($hide_footer != 1) {
      include 'footer.php';
  }
?>